package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aigestudio.wheelpicker.WheelPicker;
import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.CertInfo;
import com.epfresh.supplier.entity.LocalUploadFileEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnsureCompanyActivity extends BaseActivity implements PhotoCore.PhotoResult {

//    private TextView areaEt;
//    private EditText detailEt;
//    private EditText name;
//    private EditText edOrg;
//    private TextView number;


    CommonInputItem ciCompany;
    CommonInputItem ciId;
    CommonInputItem ciName;
    CommonInputItem ciPhone;


    private RelativeLayout rlCompany;
    private View rlError;
    private View pbCompany;
    private ImageView company_pic;
//    private RelativeLayout rlCompany2;
//    private View rlError2;
//    private View pbCompany2;
//    private ImageView company_pic2;

    private ImageView currentIv;
    private TextView tvBtn;
    private TextView tvCache;


    Context mContext;
    private int imgWidth;
    private int imgHeight;
    private PhotoCore photoCore;

    private String fileTogetherPath = FileUtil.getImgCacheDir() + "/" + "commpany";
    private String filePath = fileTogetherPath;

    private String fileFrPath = FileUtil.getImgCacheDir() + "/" + "commpany2";

    String provinceId = "";
    String cityId = "";
    String districtId = "";
    String provinceName = "";
    String cityName = "";
    String districtName = "";
    private String cityname;

    private View rlRefuse;
    private View rlBottom;
    private TextView tvRefuseContent;
    boolean isFirst;
    private LinearLayout llChooseType;
    private String remark;


    String certStatus;
    View vWarning;

    private BottomSheetDialog bottomSheetCompany;
    private List<String> typeList = new ArrayList<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ensure_company);
        if (savedInstanceState != null) {
            getIntent().putExtra("isFirst", savedInstanceState.getBoolean("isFirst"));
            getIntent().putExtra("certInfo", savedInstanceState.getString("certInfo"));
            getIntent().putExtra("certType", savedInstanceState.getString("certType"));
            getIntent().putExtra("merchantId", savedInstanceState.getString("merchantId"));
        }
        initBottomSheetUnitDialog();
        certStatus = getIntent().getStringExtra("certType");
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        remark = getIntent().getStringExtra("remark");

        ciCompany = (CommonInputItem) findViewById(R.id.ci_company_id);
        ciId = (CommonInputItem) findViewById(R.id.ci_id_card);
        ciName = (CommonInputItem) findViewById(R.id.ci_name);
        ciPhone = (CommonInputItem) findViewById(R.id.ci_company_phone);
        llChooseType = findViewById(R.id.ll_choose_type);
        llChooseType.setOnClickListener(this);


//        areaEt = (TextView) findViewById(R.id.area);
        company_pic = (ImageView) findViewById(R.id.company_pic);

        rlCompany = (RelativeLayout) findViewById(R.id.rl_company);
        rlError = findViewById(R.id.rl_error);
        pbCompany = findViewById(R.id.rl_pb);
        company_pic = (ImageView) findViewById(R.id.company_pic);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
//        rlCompany2 = (RelativeLayout) findViewById(R.id.rl_company2);
//        rlError2 = findViewById(R.id.rl_error2);
//        pbCompany2 = findViewById(R.id.rl_pb2);
//        company_pic2 = (ImageView) findViewById(R.id.company_pic2);

        rlRefuse = findViewById(R.id.rl_refuse_reason);
        tvRefuseContent = (TextView) findViewById(R.id.tv_refuse_content);

        vWarning = findViewById(R.id.ll_warning_ensure);
        mContext = this;
//        String s = "企业认证 <font color=\"#ff0000\">*</font>";
//        basetitle.setText(Html.fromHtml(s));
        basetitle.setText("申请开店");
        baseback.setVisibility(View.VISIBLE);
        fileTogetherPath = fileTogetherPath + "_" + getUser().getAccountId();
        filePath = fileTogetherPath;
        fileFrPath = fileFrPath + "_" + getUser().getAccountId();

//        imgWidth = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.designedDP2px(80));
//        if (imgWidth > LocalDisplay.designedDP2px(160)) {
//            imgWidth = LocalDisplay.designedDP2px(160);
//        }

        imgWidth = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(48)) / 2;
        imgHeight = imgWidth * 204 / 282;
//        imgHeight = imgWidth * 337 / 448;
        reSizeIv(rlCompany);
//        reSizeIv(rlCompany2);

        photoCore = new PhotoCore(this, this);
        photoCore.setCrop(false);
        photoCore.setRatio(4, 3);
        photoCore.setRatio(4, 3);
        photoCore.setResultHeight(1200);
        photoCore.setResultWidth(1200);
//        loadImage(Uri.fromFile(new File(fileTogetherPath)).toString(), company_pic);
//        loadImage(Uri.fromFile(new File(fileFrPath)).toString(), company_pic2);

//        loadPicInfo();
//        updateInfo();
//        company_pic2.setOnClickListener(this);
        company_pic.setOnClickListener(this);
        tvBtn.setOnClickListener(this);
        rightbtn.setText(getString(R.string.help));
        rightbtn.setTextColor(0xff898989);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(this);


        tvCache = (TextView) findViewById(R.id.tv_save_cache);
        tvCache.setOnClickListener(this);
        rlBottom = findViewById(R.id.v_bottom);
        CertInfo ci = null;
        if (isFirst) {
            ci = DataManager.getInstance().getCertInfo();
            initData(ci);
        } else {
            String certInfo = getIntent().getStringExtra("certInfo");
            if (certInfo != null) {
                ci = new Gson().fromJson(certInfo, CertInfo.class);
            }
            initData(ci);
            //审核中
            if ("1".equals(certStatus)) {
                certIng();
                vWarning.setVisibility(View.VISIBLE);
                vWarning.setOnClickListener(this);
                findViewById(R.id.iv_company_add).setVisibility(View.INVISIBLE);
            } else if ("3".equals(certStatus)) {//认证失败
                certFail();
                requestCertificateRefuse();
            } else if ("2".equals(certStatus)) {//认证成功
                certSucceed();
                vWarning.setVisibility(View.VISIBLE);

                vWarning.setOnClickListener(this);
                findViewById(R.id.iv_company_add).setVisibility(View.INVISIBLE);
            } else {
                certUn();
            }
        }


    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("certInfo", getIntent().getStringExtra("certInfo"));
        outState.putString("certType", getIntent().getStringExtra("certType"));
        outState.putString("merchantId", getIntent().getStringExtra("merchantId"));
        outState.putBoolean("isFirst", isFirst);
        super.onSaveInstanceState(outState);
    }

    public void initData(CertInfo certInfo) {
        if (certInfo != null && "1".equals(certInfo.getType())) {
            ciCompany.setContentText(certInfo.getName());

            ciCompany.setSelectionLast();
            picId = certInfo.getLicenceImgId();
            ciPhone.setContentText(certInfo.getLegalPersonPhone());
            ciName.setContentText(certInfo.getLegalPersonName());
            ciId.setContentText(certInfo.getLicenceNo());
            picId = certInfo.getLicenceImgId();
            loadImage(certInfo.getLicenceImgIdUrl(), company_pic);
        }
        if (!TextUtils.isEmpty(remark)) {
            tvRefuseContent.setText(remark);
            rlRefuse.setVisibility(View.VISIBLE);
        }
    }

    //审核中
    public void certIng() {
        rlBottom.setVisibility(View.GONE);
        ciCompany.setEditable(false);
        ciId.setEditable(false);
        ciName.setEditable(false);
        ciPhone.setEditable(false);

    }

    //审核失败
    public void certFail() {
        rlBottom.setVisibility(View.VISIBLE);
        tvCache.setVisibility(View.GONE);
        tvBtn.setText("重新提交");

    }

    //审核成功
    public void certSucceed() {
        rlBottom.setVisibility(View.GONE);
        ciCompany.setEditable(false);
        ciId.setEditable(false);
        ciName.setEditable(false);
        ciPhone.setEditable(false);
    }

    //未审核
    public void certUn() {
        rlBottom.setVisibility(View.VISIBLE);
        tvCache.setVisibility(View.GONE);
        tvBtn.setText("提交");
    }

    public void reSizeIv(View iv) {
        ViewGroup.LayoutParams lp = iv.getLayoutParams();
        lp.height = imgHeight;
        lp.width = imgWidth;

        iv.setLayoutParams(lp);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ll_choose_type:
                if (!TextUtils.isEmpty(remark)) {
                    T.toast("如需修改，请联系客服：400-0588-198");
                    break;
                }
                showUnit();
                break;
            case R.id.area:
                break;

            case R.id.company_pic:
                filePath = fileTogetherPath;
                currentIv = company_pic;
                if ("1".equals(certStatus)) {//认证中
                    toast("认证中，不能修改");
                } else if ("2".equals(certStatus)) {
                    toast("已认证");
                } else {//认证失败
                    photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, rlError.getVisibility() != View.GONE);
                }
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.rightbtn:
                help();
                break;
            case R.id.tv_save_cache:
                saveCache();
                break;
            case R.id.sure:
            case R.id.tv_btn:
                String name = ciCompany.getContentText();
                if (name == null || "".equals(name)) {
                    toast("请填写您的企业名称");
                    return;
                }

                if (name.length() < 6) {
                    toast("企业名称不能少于6个字");
                    return;
                }
                if (!VerificationUtils.isValid(name)) {
                    toast(getString(R.string.illegal_input, "企业名称"));
                    return;
                }
                name = ciId.getContentText();
                if (name == null || "".equals(name)) {
                    toast("请填写营业执照编号");
                    return;
                }
                if (!VerificationUtils.isValid(name)) {
                    toast(getString(R.string.illegal_input, "营业执照编号"));
                    return;
                }
                if (name.length() != 15 && name.length() != 18) {
                    toast("请输入15或18位营业执照编号");
                    return;
                }

                name = ciName.getContentText();
                if (name == null || "".equals(name)) {
                    toast("请填写您企业的法人代表名称");
                    return;
                }
                if (!VerificationUtils.isValid(name)) {
                    toast(getString(R.string.illegal_input, "法人姓名"));
                    return;
                }
                name = ciPhone.getContentText();
                if (name == null || "".equals(name)) {
                    toast("请填写企业法人手机号");
                    return;
                }
                if (name.length() != 11) {
                    toast("请填写合法的手机号");
                    return;
                }
                if (!VerificationUtils.isValid(name)) {
                    toast(getString(R.string.illegal_input, "法人手机号"));
                    return;
                }

                if (TextUtils.isEmpty(picId)) {
                    toast("请上传营业执照");
                    return;
                }

//                if (picId == null || "".equals(picId)) {
//                    toast("请上传营业执照副本");
//                    return;
//                }

                requestCertificate(false);


                break;

            case R.id.ll_warning:
                intoPhone();
                break;
        }
    }

    private void intoPhone() {
        String servicePhone = BaseApplication.getDoc().getServicePhone();
        String[] split = servicePhone.split("：");
        if (split == null || split.length < 2) {
            split = servicePhone.split(":");
        }
        if (split != null && split.length > 1) {
            String s = split[split.length - 1];
            s = s.replace("-", "");
            s.replace("－", "");
            if (VerificationUtils.isNumeric(s)) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + s));//调出来拨打页面；
                startActivity(intent);
            }
        }
    }

    private void saveCache() {
        if (isContentEmpty()) {
            toast("请填写信息");
            return;
        }
        requestCertificate(true);
    }

    private boolean isContentEmpty() {

        if (!TextUtils.isEmpty(ciId.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciName.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciPhone.getContentText())) {
            return false;
        }
        if (!TextUtils.isEmpty(ciCompany.getContentText())) {
            return false;
        }
        if (picId != null && !"".equals(picId)) {
            return false;
        }

        return true;
    }


    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_CERTIFY);
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == 1) {
            // 回传城市名字 城市ID
            if (intent != null) {
                cityname = intent.getExtras().getString("name");
                provinceId = intent.getStringExtra("provinceCode");
                cityId = intent.getStringExtra("cityCode");
                districtId = intent.getStringExtra("areaCode");
                return;
            }
            return;
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }
        photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    String picId = "";
    String picId2 = "";

    DisplayImageOptions displayImageOptions;

    private DisplayImageOptions getImageOption() {
        if (displayImageOptions == null)
            displayImageOptions = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中

                    .cacheOnDisk(false)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//
                    // 设置图片以如何的编码方式显示
                    .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                    // .decodingOptions(new Options())//设置图片的解码配置
                    // .delayBeforeLoading(int delayInMillis)//int
                    // delayInMillis为你设置的下载前的延迟时间
                    // 设置图片加入缓存前，对bitmap进行设置
                    // .preProcessor(BitmapProcessor preProcessor)
                    .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                    .build();// 构建完成
        return displayImageOptions;
    }

    public void loadImage(String path, ImageView iv) {
        ImageSize imageSize = new ImageSize(imgWidth, imgHeight);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(iv), getImageOption(), imageSize, null, null);

    }

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:

                    break;
                case HttpRequest.FAIL_NO_NET:

                    break;
                case HttpRequest.FAIL_NET_FAULT:

                default:

                    break;
            }
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onStart(Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            showProgress(requestTag.action);
            hideError(requestTag.action);
        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }
            File f = null;
            switch (requestTag.action) {
                case R.id.company_pic:
                    picId = id + "";
                    f = new File(fileTogetherPath);
                    updatePicInfo(f, id, "company_img_" + getUser().getAccountId());
                    break;
                case R.id.company_pic2:
                    picId2 = id + "";
                    f = new File(fileFrPath);
                    updatePicInfo(f, id, "company_img_2" + getUser().getAccountId());
                    break;
                default:
                    break;
            }
        }
    };

    private void showProgress(int action) {
        switch (action) {
            case R.id.company_pic:
                pbCompany.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void hideProgress(int action) {
        switch (action) {
            case R.id.company_pic:
                pbCompany.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void showError(int action) {
        switch (action) {
            case R.id.company_pic:
                rlError.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void hideError(int action) {
        switch (action) {
            case R.id.company_pic:
                rlError.setVisibility(View.GONE);
                break;
            case R.id.company_pic2:
                break;
            default:
                break;
        }
    }

    RequestTag tag = new RequestTag();

    public void uploadImage(String filePath, int id) {

        L.d("uploadfile", "-------" + SystemClock.currentThreadTimeMillis());
        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            data.setCmd(AppSupplyRouterConstant.cmd_account_file_upload);
            //data.setToken(getUser().getToken());

            data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);

            data.setParameters(map);


            tag.tag = AppSupplyRouterConstant.cmd_account_file_upload;
            tag.action = id;
            request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OnRequestListener<CertInfo> onResquestListener = new OnRequestListener<CertInfo>() {
        @Override
        public CertInfo jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, CertInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<CertInfo> response, Object tag) {
            hideProgressDialog();
            CertInfo responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {

                DataManager.getInstance().setCertInfo(responseElement);
                boolean isScratch = false;
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag rt = (RequestTag) tag;
                    isScratch = rt.type == 0 ? false : true;

                }
                if (isFirst && !isScratch) {
                    intoBank();
                } else if (isFirst && isScratch) {
                    toast("保存成功");
                } else {
                    if (getIntent().getBooleanExtra("isMineIn", false)) {
                        intoHome();
                    } else {
                        intoStoreEnsureAndOpen();
                    }
                }

            } else {

            }
        }
    };

    public void intoBank() {
        Intent intent = new Intent(this, BankActivity.class);

        intent.putExtra(Constant.TYPE, 1);
        intent.putExtra("card_count", getStoreInfo().getBankCardCount());
        intent.putExtra("userType", 2);
        intent.putExtra("isFirst", isFirst);
        intent.putExtra("remark", remark);
        startActivity(intent);
    }

    public void intoStoreEnsureAndOpen() {

        getStoreInfo().setCertStatus("1");
        updateStoreInfo(getStoreInfo());
        Intent intent = new Intent(this, StoreEnsureAndOpenActivity.class);
        startActivity(intent);
        finish();
    }

    public void intoHome() {

        getStoreInfo().setCertStatus("1");
        updateStoreInfo(getStoreInfo());
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    public void requestCertificate(boolean isScratch) {
        String merchantId = getIntent().getStringExtra("merchantId");
        String nameStr = ciCompany.getContentText();
        String numberStr = ciId.getContentText();
        String orgCode = ciPhone.getContentText();

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        //data.setCmd("account/enterpriseCert");
        data.setCmd(AppSupplyRouterConstant.cmd_account_account_enterpriseCert);
        //data.setToken(getUser().getToken());

        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();

        map.put("name", nameStr);
        if (isFirst) {
            map.put("status", "-1");
        }
        map.put("accountId", getUser().getAccountId());
        map.put("licenceNo", numberStr);
        map.put("licenceImgId", picId);
//        map.put("orgCodeImgId", picId2);
        map.put("legalPersonPhone", orgCode);
        map.put("legalPersonName", ciName.getContentText());
        map.put("merchantId", merchantId);

//        map.put("address", areaEt.getText().toString() + detailEt.getText().toString());

        data.setParameters(map);
        RequestTag tag = new RequestTag();
        tag.tag = AppSupplyRouterConstant.cmd_account_account_enterpriseCert;
        tag.type = isScratch ? 1 : 0;
        request(data, tag, onResquestListener);
    }

    public void saveInfo() {
        String nameStr = ciCompany.getContentText();
        String numberStr = ciId.getContentText();
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("licenceNo_" + getUser().getAccountId(), numberStr);
        edit.putString("licenceName_" + getUser().getAccountId(), nameStr);


//        String addressDetailStr = detailEt.getText().toString();
//        String addressAreaStr = areaEt.getText().toString();

        edit.putString("licenceOrg_" + getUser().getAccountId(), ciPhone.getContentText());
//        edit.putString("licenceArea_" + getUser().getAccountId(), addressAreaStr);
//        edit.putString("licenceDetail_" + getUser().getAccountId(), addressDetailStr);
        edit.putString("licenceP_" + getUser().getAccountId(), provinceId);
        edit.putString("licenceC_" + getUser().getAccountId(), cityId);
        edit.putString("licenceD_" + getUser().getAccountId(), districtId);

        edit.commit();
    }

    public void updateInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String num = sp.getString("licenceNo_" + getUser().getAccountId(), "");
        String nameStr = sp.getString("licenceName_" + getUser().getAccountId(), "");
        ciCompany.setContentText(num);
        ciId.setContentText(nameStr);

        provinceId = sp.getString("licenceP_" + getUser().getAccountId(), "");
        cityId = sp.getString("licenceC_" + getUser().getAccountId(), "");
        districtId = sp.getString("licenceD_" + getUser().getAccountId(), "");
//        detailEt.setText(sp.getString("licenceDetail_" + getUser().getAccountId(), ""));
        ciPhone.setContentText(sp.getString("licenceOrg_" + getUser().getAccountId(), ""));
    }

    public void updatePicInfo(File f, int id, String key) {
        long lastModified = f.lastModified();
        long totalSpace = f.getTotalSpace();
        LocalUploadFileEntity localUploadFileEntity = new LocalUploadFileEntity();
        localUploadFileEntity.setId(id);
        localUploadFileEntity.setModified(lastModified);
        localUploadFileEntity.setTotalSpace(totalSpace);
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, localUploadFileEntity.toString());
        edit.commit();
    }

    private void loadPicInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String result = sp.getString("company_img_" + getUser().getAccountId(), "");

        picId = initPicId(result, fileTogetherPath, company_pic.getId());
        result = sp.getString("company_img_2" + getUser().getAccountId(), "");

    }

    private String initPicId(String result, String filePath, int id) {
        L.d("file", "" + filePath + "--result:" + result);
        File f = new File(filePath);
        if (!TextUtils.isEmpty(result)) {
            LocalUploadFileEntity localUploadFileEntity = LocalUploadFileEntity.getLocalUploadFileEntity(result);
            L.d("file", "---------");
            if (localUploadFileEntity != null) {

                boolean isUpload = localUploadFileEntity.isUpload(f.lastModified(), f.getTotalSpace());
                L.d("file", "1." + localUploadFileEntity.getModified() + "--" + localUploadFileEntity.getTotalSpace());
                L.d("file", "2." + f.lastModified() + "--" + f.getTotalSpace());
                if (isUpload) {
                    return localUploadFileEntity.getId() + "";
                }
            }
        }
        if (f.exists()) {
            showError(id);
        }

        return "";
    }


    @Override
    public void onSuccess(String path) {
        loadImage(path, currentIv);

        uploadImage(filePath, currentIv.getId());
    }

    @Override
    public void onFail(String msg) {
        toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        uploadImage(filePath, currentIv.getId());
    }

    @Override
    protected void onDestroy() {
        if (photoCore != null) {
            photoCore.onDestory();
        }
        RequestManager.getInstance().cancel(tag);
        RequestManager.getInstance().cancel("account/enterpriseCert");
//        saveInfo();
        super.onDestroy();
    }


    public void requestCertificateRefuse() {

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_account_account_certInfo);
        //data.setToken(getUser().getToken());

        RequestTag tag = new RequestTag();
        tag.type = RequestTag.TYPE_CURRENT;
        tag.tag = AppSupplyRouterConstant.cmd_account_account_certInfo;
        request(data, tag, new OnRequestListener<Map<String, String>>() {
            @Override
            public Map<String, String> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<Map<String, String>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<Map<String, String>> response, Object tag) {

                Map<String, String> responseElement = response.getResponseElement();

//                "remark": "", 拒绝原因
//                "status": 1, 审核状态
//                "type": 2 认证类型
                if (responseElement != null) {
                    String remark = responseElement.get("remark");
                    String type = responseElement.get("type");
                    if (remark != null && "2".equals(type)) {
                        tvRefuseContent.setText(remark);
                        rlRefuse.setVisibility(View.VISIBLE);
                    }
                }

            }
        });
    }

    private void initBottomSheetUnitDialog() {
        typeList.add("个人认证");
        typeList.add("企业认证");
        View view = View.inflate(this, R.layout.companytype, null);
        final WheelPicker wheelPicker = view.findViewById(R.id.main_wheel);
        TextView cancel = view.findViewById(R.id.tv_cancel);
        TextView define = view.findViewById(R.id.tv_define);
        wheelPicker.setData(typeList);
        bottomSheetCompany = new BottomSheetDialog(this);
        bottomSheetCompany.setCancelable(true);
        bottomSheetCompany.setContentView(view);
        bottomSheetCompany.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {}
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetCompany.dismiss();
            }
        });
        define.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetCompany.dismiss();
                if (typeList.get(wheelPicker.getCurrentItemPosition()).equals("个人认证")) {
                    Intent intent = new Intent(EnsureCompanyActivity.this, EnsurePersonActivity.class);
                    intent.putExtra("remark", remark);
                    intent.putExtra("isFirst", isFirst);
                    intent.putExtra("merchantId", getIntent().getStringExtra("merchantId"));
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private void showUnit() {
        bottomSheetCompany.show();
    }


}

